#pragma once

#include <iostream>
#include <string>
#include <cstdio>
#include <cerrno>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define DefaultFd -1
#define Creater 1
#define User 2
#define Read O_RDONLY
#define Write O_WRONLY
#define BaseSize 4096

const std::string comm_path = "./myfifo";

class NamePipe
{
private:
    bool OpenNamePipe(int mode)
    {
        _fd = open(_fifo_path.c_str(), mode);
        if (_fd < 0)
            return false;
        return true;
    }

public:
    NamePipe(std::string fifo_path, int who)
        : _fifo_path(fifo_path), _id(who)
    {
        if (_id == 1)
        {
            int res = mkfifo(_fifo_path.c_str(), 0666);
            if (res != 0)
            {
                perror("mkfifo");
            }
            std::cout << "Creater create Pipe" << std::endl;
        }
    }
    ~NamePipe()
    {
        if (_id == 1)
        {
            int res = unlink(_fifo_path.c_str());
            if (res != 0)
            {
                perror("mkfifo");
            }
            std::cout << "Creater remove Pipe"<<std::endl;
        }
        if(DefaultFd != -1) close(_fd);
    }

    bool OpenForRead()
    {
        return OpenNamePipe(Read);
    }
    bool OpenForWrite()
    {
        return OpenNamePipe(Write);
    }

    int ReadPipe(std::string *out)
    {
        char buffer[BaseSize];
        int n = read(_fd,buffer,sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            *out = buffer;
        }
        return n;
    }
    int WritePipe(const std::string &in)
    {
        return write(_fd,in.c_str(),in.size()); 
    }

private:
    const std::string _fifo_path;
    int _id;
    int _fd;
};
